package com.ztesoft.test.service.ciweb;

import java.io.IOException;

import com.alibaba.druid.stat.DruidStatService;
import com.alibaba.druid.util.Utils;

import ci.web.annotaction.PathParam;
import ci.web.annotaction.Router;
import ci.web.core.CiContext;
import ci.web.router.CiFile;

@Router("druid")
public class DruidStat {

	private DruidStatService statService = DruidStatService.getInstance();
	private String resoucePath = "support/http/resources";

	public DruidStat() {
	}

	@Router("*")
	public void api(CiContext ctx) throws IOException {
		if (ctx.path().endsWith(".json") == false) {
			loadFile(ctx);
			return;
		}
		String url = ctx.uri();
		int idx = url.lastIndexOf('/');
		url = url.substring(idx);
		// System.out.println(url);
		String ret = statService.service(url);
		ctx.send(ret);
	}

	private void loadFile(CiContext ctx) throws IOException {
		String filePath = resoucePath + ctx.path().replace("/druid", "");
		if (filePath.endsWith(".jpg")) {
			byte[] bytes = Utils.readByteArrayFromResource(filePath);
			if (bytes != null) {
				ctx.send(bytes);
			}
			return;
		}
		String text = Utils.readFromResource(filePath);
		if (text == null) {
			ctx.redirect("/index.html");
			return;
		}
		if (filePath.endsWith(".css")) {
			ctx.setContentType("text/css;charset=utf-8");
		} else if (filePath.endsWith(".js")) {
			ctx.setContentType("text/javascript;charset=utf-8");
		}
		ctx.send(text);
	}

}
